﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using System.Linq;
namespace Admin.NET.Application;
/// <summary>
/// 试场服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ShichangService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Shichang> _rep;
    private readonly SqlSugarRepository<Kaoshi> _kaoshiRep;
    private readonly SqlSugarRepository<Shichang> _shichangRep;
    private readonly SqlSugarRepository<Kaosheng> _kaoshengRep;

    public ShichangService(SqlSugarRepository<Shichang> rep, SqlSugarRepository<Kaoshi> kaoshiRep, SqlSugarRepository<Shichang> shichangRep, SqlSugarRepository<Kaosheng> kaoshengRep)
    {
        _rep = rep;
        _kaoshiRep = kaoshiRep;
        _shichangRep = shichangRep;
        _kaoshengRep = kaoshengRep;
    }

    /// <summary>
    /// 分页查询试场
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<ShichangOutput>> Page(ShichangInput input)
    {
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.ShiChangNum.Contains(input.SearchKey.Trim())
                || u.Address1.Contains(input.SearchKey.Trim())
                || u.Address2.Contains(input.SearchKey.Trim())
                || u.Weizhi.Contains(input.SearchKey.Trim())
            )
            .WhereIF(input.KaoshiId>0, u => u.KaoshiId == input.KaoshiId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.ShiChangNum), u => u.ShiChangNum.Contains(input.ShiChangNum.Trim()))
            .WhereIF(input.Renshu>0, u => u.Renshu == input.Renshu)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Address1), u => u.Address1.Contains(input.Address1.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Address2), u => u.Address2.Contains(input.Address2.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Weizhi), u => u.Weizhi.Contains(input.Weizhi.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Kaoshi>((u, kaoshiid) => u.KaoshiId == kaoshiid.Id )
            .OrderBy(u => u.CreateTime)
            .Select((u, kaoshiid) => new ShichangOutput
            {
                Id = u.Id,
                KaoshiId = u.KaoshiId, 
                KaoshiIdName = kaoshiid.Name,
                ShiChangNum = u.ShiChangNum,
                Renshu = u.Renshu,
                Address1 = u.Address1,
                Address2 = u.Address2,
                Weizhi = u.Weizhi,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加试场
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddShichangInput input)
    {
        var entity = input.Adapt<Shichang>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除试场
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteShichangInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
        //await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新试场
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateShichangInput input)
    {
        var entity = input.Adapt<Shichang>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取试场
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<Shichang> Detail([FromQuery] QueryByIdShichangInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取试场列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<ShichangOutput>> List([FromQuery] ShichangInput input)
    {
        return await _rep.AsQueryable().Select<ShichangOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取考试列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "KaoshiKaoshiIdDropdown"), HttpGet]
    public async Task<dynamic> KaoshiKaoshiIdDropdown()
    {
        return await _rep.Context.Queryable<Kaoshi>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 保存考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Save")]
    public async Task Save(SaveShichangInput input)
    {
        foreach (var item in input.data)
        {
            var kaoshi = await _kaoshiRep.GetFirstAsync(u => u.Id == item.KaoshiId) ?? throw Oops.Oh("考试不存在");
            var entity = item.Adapt<Shichang>();
            if (entity.Id == 0)
            {
                await _rep.InsertAsync(entity);
            }
            else
            {
                await _rep.UpdateAsync(entity);
            }
        }
        var list = await _rep.AsQueryable().Where(p => p.KaoshiId == input.KaoshiId).ToListAsync();
        foreach (var item in list)
        {
            if (input.data.FirstOrDefault(p => p.KaoshiId == item.KaoshiId && p.ShiChangNum == item.ShiChangNum) == null)
            {
                await _rep.DeleteAsync(item);
            }
        }
    }

    /// <summary>
    /// 保存考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "AutoShichangRenshu")]
    public async Task AutoShichangRenshu(AutoShichangRenshuInput input)
    {
        long kaoshiId = input.KaoshiId;
        var shichangs = await _rep.AsQueryable().Where(p => p.KaoshiId == kaoshiId).ToListAsync() ;
        var kaoshengs = await _kaoshengRep.AsQueryable().Where(p => p.KaoshiId == kaoshiId).ToListAsync();
        var zongRenshu = kaoshengs.Count;
        var shichangCount = shichangs.Count;
        int renshu = (int)Math.Ceiling(zongRenshu * 1.0 / shichangCount);
        int cnt = 0;
        foreach (var item in shichangs)
        {
            cnt ++;
            if(cnt == shichangs.Count)
            {
                item.Renshu = zongRenshu - (shichangs.Count -1 )*renshu;
            }
            else
            {
                item.Renshu = renshu;
            }
            await _rep.UpdateAsync(item);
        }
    }
    

}

